package com.ruoyi.voucher.service.impl;

import com.alibaba.excel.EasyExcel;
import com.ruoyi.voucher.domain.Voucher;
import com.ruoyi.voucher.listener.VoucherDataListener;
import com.ruoyi.voucher.mapper.VocherMapper;
import com.ruoyi.voucher.service.IVoucherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author:cocoKe
 * @Description:
 * @VERSON:1.8
 * @create:2025-03-01 10:29
 * @Date:2025/3/1
 */
@Service
public class VoucherServiceImpl implements IVoucherService {


    @Resource
    private VocherMapper vocherMapper;

    /**
     * 导出凭证数据
     *
     * @param response
     * @param voucher
     */

    // 定义常量提升可维护性
    private static final String FILE_NAME_PREFIX = "demo_";
    private static final String SHEET_NAME = "模板";
    private static final String DOWNLOADS_DIR = "Downloads";
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");

    @Override
    public void export(HttpServletResponse response, Voucher voucher) {
        List<Voucher> vouchers = vocherMapper.selectVoucherList(voucher);


        Stream.of(vouchers).forEach(System.out::println);
        // 生成线程安全的时间戳
        String timestamp = LocalDateTime.now().format(DATE_FORMAT);
        String fileName = FILE_NAME_PREFIX + timestamp + ".xlsx";

        // 配置HTTP响应头（关键修正：通过响应流返回文件）
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        try (OutputStream out = response.getOutputStream()) {
            EasyExcel.write(out, Voucher.class)
                    .sheet(SHEET_NAME)
                    .doWrite(vouchers);
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e); // 根据实际异常体系调整
        }
    }

    @Override
    public void importData(MultipartFile file) {
        // 解析Excel文件


        try {
            EasyExcel.read(file.getInputStream(),
                    Voucher.class,
                    new VoucherDataListener(vocherMapper)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}